import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

// DELETE delete a copy
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        copy_count: {
          decrement: 1
        }
      }
    })
    const { id } = params
    // 先查询文案所属用户
    const copy = await prisma.vms_copy.findUnique({
      where: { id }
    })
    
    if (!copy) {
      return NextResponse.json(
        { error: '未找到文案' },
        { status: 404 }
      )
    }
    
    // 检查当前用户是否有权限删除
    if (copy.user_id !== userid) {
      return NextResponse.json(
        { error: '无权删除他人文案' },
        { status: 403 }
      )
    }
    
    // First delete all scripts associated with this copy
    await prisma.vms_script.deleteMany({
      where: {
        copy_id: id
      }
    })
    
    // Then delete the copy itself
    await prisma.vms_copy.delete({
      where: {
        id
      }
    })


    // 统计话题下所有文案数量和已完成文案数量
    const [totalCount, finishedCount] = await Promise.all([
      prisma.vms_copy.count({
        where: { 
          topic_id: copy.topic_id || undefined
        }
      }),
      prisma.vms_copy.count({
        where: { 
          topic_id: copy.topic_id || undefined,
          status: '已完成'
        }
      })
    ])

    // 更新话题的文案统计信息
    await prisma.vms_topic.update({
      where: { id: copy.topic_id || undefined },
      data: {
        copy_num: totalCount,
        copy_finished_num: finishedCount
      }
    })
    
    return NextResponse.json({ message: 'Copy deleted successfully' }, { status: 200 })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to delete copy' },
      { status: 500 }
    )
  }
}

// GET get a single copy by ID
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const { id } = params
    
    const copy = await prisma.vms_copy.findUnique({
      where: {
        id
      }
    })
    
    if (!copy) {
      return NextResponse.json(
        { error: 'Copy not found' },
        { status: 404 }
      )
    }
    
    return NextResponse.json(copy, { status: 200 })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch copy' },
      { status: 500 }
    )
  }
}
